package cn.zqh.brand.service.impl;

import cn.zqh.bean.api.CommonResult;
import cn.zqh.bean.api.ResultCode;
import cn.zqh.bean.bo.*;
import cn.zqh.brand.client.CommodityClient;
import cn.zqh.brand.client.UserClient;
import cn.zqh.brand.config.BSException;
import cn.zqh.brand.holder.LoginUserHolder;
import cn.zqh.brand.mapper.ShopCarMapper;
import cn.zqh.brand.service.ShopCarService;
import cn.zqh.uuid.utils.SnowflakeId;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zqh
 * @since 2023-02-28
 */
@Service
public class ShopCarServiceImpl extends ServiceImpl<ShopCarMapper, ShopCar> implements ShopCarService {

    @Resource
    private ShopCarMapper shopCarMapper;

    @Autowired
    private CommodityClient commodityClient;

    @Autowired
    private LoginUserHolder loginUserHolder;

    @Autowired
    private UserClient userClient;

    @Autowired
    private RestTemplate restTemplate;


    /**
      * @Author: zqh
      * @Date:
      * @Description: 把商品加入购物车
    */
    @Override
    public CommonResult addCommodityToCar(String commodityId, Integer number) {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        if (currentUser == null) {
            throw new BSException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        EsCommodity commodity = commodityClient.getCommodityById(commodityId);
        if (commodity == null) {
            throw new BSException(ResultCode.AnErrorOccurredInTheRemoteCall.getCode(),ResultCode.AnErrorOccurredInTheRemoteCall.getMessage());
        }
        ShopCar shopCar = new ShopCar();
        shopCar.setCarId("car"+ SnowflakeId.nextId())
                .setUserId(currentUser.getId())
                .setCommodityId(commodityId)
                .setIsDelete(0)
                .setNumber(number)
                .setMoney(number * commodity.getPrice());

        int i = shopCarMapper.insert(shopCar);
        if (i != 1){
            return CommonResult.failed();
        }

        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 用户查询自己的购物车
    */
    @Override
    public CommonResult getOwnShopCar(Integer page, Integer size) {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        if (currentUser == null) {
            throw new BSException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        page = (page - 1) * size;
        List<ShopCar> lists = shopCarMapper.getOwnShopCarByMapper(currentUser.getId(),page,size);
        ArrayList<Object> list = new ArrayList<>();
        for (ShopCar shopCar : lists) {
            CommonResult forUser = restTemplate.getForObject("http://127.0.0.1:9501/user/getUserById?userId=" + currentUser.getId(), CommonResult.class);
            String s1 = JSON.toJSONString(forUser.getData());
            User user = JSON.parseObject(s1, User.class);
//            User user = userClient.getUserById(shopCar.getUserId());
            CommonResult forObject1 = restTemplate.getForObject("http://127.0.0.1:9801/commodity/getCommodityById?id=" + shopCar.getCommodityId(), CommonResult.class);
            String s2 = JSON.toJSONString(forObject1.getData());
            EsCommodity commodity = JSON.parseObject(s2, EsCommodity.class);
//            EsCommodity commodity = commodityClient.getCommodityById(shopCar.getCommodityId());
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("shopCar",shopCar);
            hashMap.put("user",user);
            hashMap.put("commodity",commodity);
            list.add(hashMap);
        }
        return CommonResult.success(list);

    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 把商品移除购物车
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult removeItemsFromcCar(String shopCarId) {
        int i = shopCarMapper.deleteById(shopCarId);
        if (i != 1){
            return CommonResult.failed();
        }

        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 修改购物车中商品的数量
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult updateCarCommodityInfo(String shopCarId, Integer number) {
        ShopCar shopCar = shopCarMapper.selectById(shopCarId);
        double v = shopCar.getMoney() / shopCar.getNumber();
        shopCar.setNumber(number)
                .setMoney(v * number);

        int i = shopCarMapper.updateById(shopCar);
        if (i != 1){
            return CommonResult.failed();
        }

        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 管理员获取所有购物车信息
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult adminGetALlShopCar(Integer page, Integer size) {
        List<ShopCar> shopCars = shopCarMapper.getAllShopCarByMapper((page - 1) * size, size);
        ArrayList<Object> list = new ArrayList<>();
        for (ShopCar shopCar : shopCars) {
            User user = userClient.getUserById(shopCar.getUserId());
            EsCommodity commodity = commodityClient.getCommodityById(shopCar.getCommodityId());
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("shopCar",shopCar);
            hashMap.put("user",user);
            hashMap.put("commodity",commodity);
            list.add(hashMap);
        }
        return CommonResult.success(list);
    }
}
